package ar.com.niktutos.util;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import ar.com.niktutos.web.TutoPlayer;

public class AjaxServletDispatcher extends HttpServlet{
	
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
    	resp.setCharacterEncoding("UTF-8");
    	resp.setContentType("text/xml;charset=UTF-8");
    	PrintWriter out = resp.getWriter();
        try {
        	//TODO verificar si el método tiene permiso
        	req.setCharacterEncoding("UTF-8");
        	String metodo = req.getParameter("method");
        	String params = req.getParameter("params");
        	String clase = req.getParameter("clazz");
        	
        	String parametros[] = params.split(",");
        	Class clases[] = new Class[parametros.length];
        	for(int i=0; i<clases.length;i++)
        		clases[i] = String.class;
        	
        	Class clazz = Class.forName(clase);
        	Object ob;
			ob = clazz.getConstructor(null).newInstance(null);
			String output = (String)ob.getClass().getMethod(metodo, clases).invoke(ob, parametros);
			
			out.print(output);

		} catch (InstantiationException | ClassNotFoundException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException | NoSuchMethodException
				| SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
        } finally {
        	out.close();
        }
   }
    

}
